<?php
/**
 * Created by PhpStorm.
 * User: don
 * Date: 17/4/6
 * Time: 上午11:32
 */

namespace App\Help;

use App\Models\File;
class Help {

    /**发送短信验证码
     * @param $mobile
     * @param $content
     * @return mixed
     */
    public static function sendSmsCode($mobile, $content){


        $sms = new SMS();

        $result = $sms->sendSMS($mobile,$content);
        //$result = $shuodaSdk->overAge();
        //$result = $shuodaSdk->checkKeyWord('诈骗');
        //$result = $shuodaSdk->queryStatus();
        //$result = $shuodaSdk->call();
       return $sms->execResult($result);
    }


    /**生成验证码
     * @return string
     */
    public static function getCheckCode(){
        $code = '';
        for ($i = 0; $i < 6; $i++) {
            $code = $code . substr(str_shuffle('0123456789'), 0, 1);
        }
        return $code;
    }

    /**生成随机密码
     * @param int $length
     * @return string
     */
    public static function getUserPassWd($length = 6) {
        // 密码字符集，可任意添加你需要的字符
        $chars = '0123456789';
        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }

        return $password;
    }

    public static function getOrderNumber(){
        return date('Ymdhis').rand(1,1000) . uniqid();
    }

    /**
     *生成二维码
     * @param string $param
     * @return string
     */
    public static function QRCodes($param){

        include __DIR__.'/phpqrcode.php';

        $errorCorrectionLevel = 'H';//容错级别
        $matrixPointSize = 16;//生成图片大小
        $name = Help::getUserPassWd();
//        echo $name;exit;
        $path =  __DIR__ . '/../../upload/QRCode/'.$name.'.png';
        //生成二维码图片
        QRcode::png($param, $path, $errorCorrectionLevel, $matrixPointSize, 2);

        $fileId = md5($path).time();
        $model = new File();
        $model->name = $name.'.png';
        $model->type = 'image/png';
        $model->ext = 'png';
        $model->size = getimagesize($path)[0];
        $model->fileHash = md5($path);
        $model->fileId = $fileId;
        $model->time = date('Y-m-d H:i:s');


        $rdate = date('Y-m-d', time());
        if(!file_exists(__DIR__.'/../../upload/' .$rdate)) {
            mkdir(__DIR__.'/../../upload/' . $rdate,0777);
        }
        if(copy($path,__DIR__.'/../../upload/' . $rdate.'/'.md5($path).'.png') && unlink($path)){
            if($model->save()){
                return $fileId;
            }
        }

    }



    /**
     * 对象转数组
     * @param $array
     * @return array
     */
    public static function  object2Array($array) {
        if (is_object($array)) {
            $array = (array)$array;
        }

        if (is_array($array)) {
            $newArray = array();
            foreach ($array as $key => $value) {
                $newArray[$key] = self::object2Array($value);
            }
            return $newArray;
        }

        return $array;
    }


    /**调取ocr 获取图片信息
     * @param $path
     * @return array|bool
     */
    public static function getOcrInfo($path){
        if (!file_exists($path)){
            return false;
        }

        $image_file = $path;

        $content = base64_encode(file_get_contents($image_file));

        $ocr = new OCR();
        $response = $ocr->ocrGet($content);

        $info = json_decode($response, true);

//        var_dump($info);exit;
        $root = $info['outputs'][0]['outputValue']['dataValue'];
        $res = json_decode(json_encode($root), true);
        $temp = explode(',', $res);

        $result = [];

        foreach ($temp as $item){
            $temp = explode(':',trim(trim(trim($item,'{')),'}'));
            $result[$temp[0]] = $temp[1];
        }

        return $result;
//        var_dump($result);exit;
//        var_dump(explode(',',$root));exit;
    }

    /**
     * 压缩图片
     * @param $path
     * @return bool
     */
    public static function updateImage($img_src, $new_img_path){

        $img_info = @getimagesize($img_src);
        $new_width = $img_info[0] >  350 ? 350 : $img_info[0];
        $new_height = $img_info[1] > 250 ? 250 : $img_info[1];
        if (!$img_info || $new_width < 1 || $new_height < 1 || empty($new_img_path)) {
            return false;
        }
        if (strpos($img_info['mime'], 'jpeg') !== false) {
            $pic_obj = imagecreatefromjpeg($img_src);
        } else if (strpos($img_info['mime'], 'gif') !== false) {
            $pic_obj = imagecreatefromgif($img_src);
        } else if (strpos($img_info['mime'], 'png') !== false) {
            $pic_obj = imagecreatefrompng($img_src);
        } else {
            return false;
        }
        $pic_width = imagesx($pic_obj);
        $pic_height = imagesy($pic_obj);
        if (function_exists("imagecopyresampled")) {
            $new_img = imagecreatetruecolor($new_width,$new_height);
            imagecopyresampled($new_img, $pic_obj, 0, 0, 0, 0, $new_width, $new_height, $pic_width, $pic_height);
        } else {
            $new_img = imagecreate($new_width, $new_height);
            imagecopyresized($new_img, $pic_obj, 0, 0, 0, 0, $new_width, $new_height, $pic_width, $pic_height);
        }
        if (preg_match('~.([^.]+)$~', $new_img_path, $match)) {
            $new_type = strtolower($match[1]);
            switch ($new_type) {
                case 'jpg':
                    imagejpeg($new_img, $new_img_path);
                    break;
                case 'gif':
                    imagegif($new_img, $new_img_path);
                    break;
                case 'png':
                    imagepng($new_img, $new_img_path);
                    break;
                default:
                    imagejpeg($new_img, $new_img_path);
            }
        } else {
            imagejpeg($new_img, $new_img_path);
        }
        imagedestroy($pic_obj);
        imagedestroy($new_img);
        return true;
    }

}